package cn.kgc.mybatis;

import cn.kgc.mybatis.entity.User;
import com.mysql.jdbc.Driver;

import java.sql.*;
import java.util.ArrayList;

/**
 * JDBC操作的流程
 * 1.导包  mysql
 * 2.注册驱动
 * 3.获取连接
 * 4.获取发送sql语句的对象
 * 5.发送sql语句处理结果集
 * 6.释放资源
 *
 *
 * 问题分析
 * 1. 获取连接的过程比较繁琐  jdbcUtil
 * 2.处理结果集的过程繁琐    commons-dbutils.jar
 * 3.释放资源存在代码冗余   jdbcUtil
 * 4.sql语句和java代码存在耦合
 * 5. 动态sql  非常繁琐  拼接
 *
 * mybatis框架   缓存机制  在一定程度上解决了持久层数据库的服务压力
 */
public class App {

    public static void main(String[] args) throws SQLException {

        // mysql的驱动对象
        Driver driver = new Driver();
        // 注册驱动
        DriverManager.registerDriver(driver);
        //获取连接
        String url = "jdbc:mysql:///java2320?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=UTF-8";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println("connection = " + connection);

        // 获取发送sql语句的对象
        String sql = "select *  from user";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        ArrayList<User> users = new ArrayList<>();
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String uname = resultSet.getString(2);
            String pwd = resultSet.getString(3);

            User user = new User().setId(id).setUsername(uname).setPassword(pwd);
            users.add(user);
        }
        System.out.println("users = " + users);

        // 释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
